package org.lds.scheduled.job.worker.scheduler.job;

import lombok.extern.slf4j.Slf4j;
import org.lds.scheduled.job.common.model.AppInstanceModel;
import org.lds.scheduled.job.common.model.dto.ResultDTO;
import org.lds.scheduled.job.common.model.request.ScheduledJobRequest;
import org.lds.scheduled.job.common.util.RestUtil;
import org.lds.scheduled.job.worker.common.constant.WorkerConstant;
import org.lds.scheduled.job.worker.loadbalancer.AppInstanceLoadBalancer;
import org.lds.scheduled.job.worker.loadbalancer.RoundAppInstanceLoadBalancer;
import org.quartz.*;
import org.springframework.core.ParameterizedTypeReference;

import java.util.List;

@Slf4j
@DisallowConcurrentExecution
public class SchedulerCommonJob implements Job {
    private AppInstanceLoadBalancer appInstanceLoadBalancer = new RoundAppInstanceLoadBalancer();

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("SchedulerCommonJob={}", this);

        try {
            JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
            String appName = (String) jobDataMap.get(WorkerConstant.APP_NAME);
            String jobName = (String) jobDataMap.get(WorkerConstant.JOB_NAME);
            List<AppInstanceModel> appInstanceModels = (List<AppInstanceModel>) jobDataMap.get(WorkerConstant.APP_INSTANCES);

            String appInstance = appInstanceLoadBalancer.getAppInstance(appInstanceModels);
            String url = "http://" + appInstance + "/api/scheduled-job/common";
            ResultDTO resultDTO = RestUtil.post(url,
                    ScheduledJobRequest.builder().appName(appName).key(jobName).build(),
                    new ParameterizedTypeReference<ResultDTO>() {});
            log.info("job end. appInstance={} resultDTO={}", appInstance, resultDTO);
        } catch (Exception e) {
            log.error("SchedulerCommonJob error", e.getMessage());
        }
    }
}
